package com.videoadmin.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.videoadmin.dao.IHistoryDAO;
import com.videoadmin.pojo.History;
import com.videoadmin.utils.HibernateUtil;

public class HistoryDAOImpl implements IHistoryDAO {
	
	/* (non-Javadoc)
	 * @see com.video.dao.IHistoryDao#saveOrUpdate(com.domain.History)
	 */
	public void saveOrUpdate(History history){
		Session s = null;
		Transaction ts = null;
		try {
			s = HibernateUtil.getSession();
			ts = s.beginTransaction();
			s.saveOrUpdate(history);
			ts.commit();
		} catch (HibernateException e) {
			if (ts != null)
				ts.rollback();
			throw e;
		} finally {
			if (s != null)
				s.close();
		}
	}
	/* (non-Javadoc)
	 * @see com.video.dao.IHistoryDao#delete(com.domain.History)
	 */
	public void delete(History history){
		Session s = null;
		Transaction ts = null;
		try {
			s = HibernateUtil.getSession();
			ts = s.beginTransaction();
			s.delete(history);
			ts.commit();
		} catch (HibernateException e) {
			if (ts != null)
				ts.rollback();
			throw e;
		} finally {
			if (s != null)
				s.close();
		}
	}
	/* (non-Javadoc)
	 * @see com.video.dao.IHistoryDao#findByHistoryId(int)
	 */
	public History findByHistoryId(int id){
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			History history = (History) s.get(History.class, id);
			return history;
		} finally {
			if (s != null)
				s.close();
		}
	}
	/* (non-Javadoc)
	 * @see com.video.dao.IHistoryDao#findByUserId(int)
	 */
	public List<History> findByUserId(int id){
		Session s=null;
		List<History> list=new ArrayList<History>();
		try{
			s = HibernateUtil.getSession();
			list=(List<History>)s.createSQLQuery("select * from History where User_Id='"+id+"'").addEntity(History.class).list();
			return list;
		}finally {
			if (s != null)
				s.close();
		}
	}
	/* (non-Javadoc)
	 * @see com.video.dao.IHistoryDao#findByMovieId(int)
	 */
	public List<History> findByMovieId(int id){
		Session s=null;
		List<History> list=new ArrayList<History>();
		try{
			s = HibernateUtil.getSession();
			list=(List<History>)s.createSQLQuery("select * from History where Movie_Id='"+id+"'").addEntity(History.class).list();
			return list;
		}finally {
			if (s != null)
				s.close();
		}
	}

}
